﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : MultiServerEngine | ServerFramework | ClientPeerRegistry.cs
// //  Created : 2016 - 02 - 16 20:53
// //  Modified: 2016 - 02 - 20 12:32
// //  ********************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using ExitGames.Logging;
using ServerFramework.Interfaces.Client;

namespace ServerFramework.Implementation.Client
{
    public class ClientPeerRegistry : IClientPeerRegistry<IClientPeer>
    {
        public ILogger Logger { get; }
        private readonly Dictionary<Guid, IClientPeer> _clientPeers;

        public ClientPeerRegistry(ILogger logger)
        {
            Logger = logger;
            _clientPeers = new Dictionary<Guid, IClientPeer>();
        }

        public bool RegisterPeer(IClientPeer clientPeer)
        {
            Logger.DebugFormat("Received register client peer request for client with id={0}", clientPeer.PeerId);

            // Do we have an entry for that client in our registry?
            if (_clientPeers.ContainsKey(clientPeer.PeerId))
            {
                Logger.ErrorFormat("Client with id={0} already registered.", clientPeer.PeerId);
                return false;
            }

            _clientPeers.Add(clientPeer.PeerId, clientPeer);
            Logger.InfoFormat("Registered client with id={0}", clientPeer.PeerId);
            return true;
        }

        public bool UnregisterClientPeer(IClientPeer clientPeer)
        {
            // Do we have that client in our registry?
            if (!_clientPeers.ContainsKey(clientPeer.PeerId)) return false;

            Logger.InfoFormat("Unregistering client peer with id {0}", clientPeer.PeerId);
            _clientPeers.Remove(clientPeer.PeerId);
            return true;
        }

        public IDictionary<Guid, IClientPeer> GetClientPeers()
        {
            return _clientPeers;
        }

        public IClientPeer GetClientPeer(Guid peerId)
        {
            return _clientPeers.FirstOrDefault(p => p.Key == peerId).Value;
        }
    }
}
